/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.stalinski.accounting;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BookingsConnector {

    private static String sUsr = "root";
    private static String sPwd = "admin";
    private static String sDB = "frbrUsers";
    private static String sTable = "bookings";
    private static Connection connection;
    private static String sHost = "localhost";
    private static String sConn = "jdbc:mysql://" + sHost + ":3306/" + sDB;

    public BookingsConnector() throws SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
        }
        try {
            connection = DriverManager.getConnection(sConn, sUsr, sPwd);
            System.out.println(connection != null);
        } catch (SQLException ex) {
        }
    }

    public void book(String id,String fn, String sn, String un, String sort, Integer amnt) throws ClassNotFoundException, SQLException {
        new ConsumersConnector().updateLastOrder(id);
        Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection(sConn, sUsr, sPwd);
        Statement st = null;
        ResultSet rs = null;
        st = connection.createStatement();

        Double actualPrice = new PricesTableConnector().getPriceFor(sort);
        Double value = Math.round(actualPrice * amnt * 100.0) / 100.0;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
        String timeString = tf.format(date);
        String dateString = df.format(date);

        String executeValues = "('"+id+"','"+dateString+"','"+timeString+"','"+fn+"','"+sn+"','"+un+"','"+sort+"',"+amnt+","+actualPrice+","+value+")";

        String execute = "INSERT INTO " + sTable + " (UID,DATE,TIME,VORNAME, NACHNAME, USER, SORT, AMOUNT, CURRENTPRICE, VALUE)" +
                "VALUES "+executeValues;
        st.execute(execute);
        new PricesTableConnector().updateStock(sort, amnt);
        connection.close();
    }
}
